<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { addressDetailAPIRes, addressAddAPIRes, addressEditAPIRes, addressDeleteAPIRes } from '@/api'
  import { useLocation } from '@/store/location'

  const { query } = useRoute()
  const router = useRouter()
  const userStore = useLocation()
  const coord = ref('')
  const mapShow = ref(false)
  const formData = ref<any>({
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    address: '',
    location: '',
    defaultAddress: 0
  })

  const onMapShow = () => {
    coord.value = formData.value.location ? `${formData.value.location.split(',')[1]},${formData.value.location.split(',')[0]}` : `${userStore.location.split(',')[1]},${userStore.location.split(',')[0]}`
    mapShow.value = true
  }
  const onSubmit = async() => {
    if (query.id) {
      await addressEditAPIRes(formData.value)
    } else {
      await addressAddAPIRes(formData.value)
    }
    router.back()
  }
  const onDelete = async() => {
    await addressDeleteAPIRes(Number(query.id))
    router.back()
  }

  onMounted(async() => {
    if (query.id) {
      const { data } = await addressDetailAPIRes({ id: Number(query.id) })
      formData.value = data
    }
    window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        console.log('location', loc)
        formData.value.location = `${loc.latlng.lat},${loc.latlng.lng}`
        formData.value.province = loc.poiaddress
        formData.value.address = loc.poiname
      }
    }, false);
  })
</script>

<template>
  <van-nav-bar left-arrow fixed placeholder safe-area-inset-top :border="false" @click-left="router.back()" />
  <van-form @submit="onSubmit" class="mt-2.5">
    <van-cell-group inset>
      <van-field
        v-model.trim="formData.name"
        required
        center
        clearable
        label="联系人"
        placeholder="请填写联系人"
        :rules="[{ required: true, message: '请填写联系人' }]"
      />
      <van-field
        v-model.trim="formData.phone"
        required
        center
        clearable
        type="tel"
        label="手机号码"
        placeholder="请填写手机号码"
        :rules="[{ required: true, message: '请填写手机号码' }]"
      />
      <van-field
        v-model.trim="formData.province"
        required
        center
        clearable
        readonly
        autosize
        is-link
        label="服务地址"
        placeholder="请选择服务地址"
        :rules="[{ required: true, message: '请选择服务地址' }]"
        @click="onMapShow"
      />
      <van-field
        v-model.trim="formData.address"
        rows="2"
        required
        autosize
        label="详细地址"
        type="textarea"
        placeholder="请填写详细地址"
        :rules="[{ required: true, message: '请填写详细地址' }]"
      />
      <van-cell center title="设为默认地址">
        <template #right-icon>
          <van-switch v-model="formData.defaultAddress" :size="20" :inactive-value="0" :active-value="1" active-color="#7C6186" />
        </template>
      </van-cell>
    </van-cell-group>
    <div class="m-4">
      <van-button round block color="#7C6186" native-type="submit">保存</van-button>
      <van-button v-if="query.id" plain round block color="#7C6186" class="mt-3" @click="onDelete">删除</van-button>
    </div>
  </van-form>
  <van-popup v-model:show="mapShow" safe-area-inset-bottom position="bottom" class="h-dvh">
    <iframe id="mapPage" width="100%" height="100%" frameborder=0 :src="`https://apis.map.qq.com/tools/locpicker?search=1&policy=1&type=1&coord=${coord}&key=M5FBZ-3VL67-3VDXK-H2EHA-ZHML3-KYFHH&referer=dingwei`"></iframe>
    <div class="absolute bottom-0 left-0 right-0 z-50 bg-white px-5 py-2.5">
      <van-button block round type="primary" size="small" @click="mapShow = false">确认选点</van-button>
    </div>
  </van-popup>
</template>